package com.example.netty.utils;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * @author feina
 * @Title: NettyUtils.java
 * @Package com.example.netty.utils
 * @Description 保存socketChannel，方便后面使用
 * @date 2023/4/23 13:38
 * @Copyright
 */

@Component
@Slf4j
public class NettyUtils {
    private SocketChannel socketChannel;

    // 等待重连时间
    private static final int WAIT_TIME = 5000;

    @Async
    public void connect() throws InterruptedException {
        boolean success = true;
        SocketChannel socketChannel = null;
        try {
            socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8088));
            socketChannel.configureBlocking(false);
            Selector selector = Selector.open();
            socketChannel.register(selector, SelectionKey.OP_READ);
        }
        catch (Exception e) {
            success = false;
            log.error("netty连接失败，{}ms后开始重连", WAIT_TIME);
            Thread.sleep(WAIT_TIME);
            log.info("netty开始重连");
            this.connect();
        }
        finally {
            if (success) {
                this.setSocketChannel(socketChannel);
                log.info("netty连接成功");
            }
        }
    }

    public void setSocketChannel(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    public SocketChannel getSocketChannel() {
        if (socketChannel == null) {
            throw new RuntimeException("socketChannel is null");
        }
        return socketChannel;
    }

}
